//
//  UIButton+YSLayout.m
//  YSKitDemo
//
//  Created by MOLBASE on 2018/8/13.
//  Copyright © 2018年 YangShen. All rights reserved.
//

#import "UIButton+YSLayout.h"

@implementation UIButton (YSLayout)

- (void)setImage:(UIImage *)image
           title:(NSString *)title
   titlePosition:(YSTitlePosition)position
         spacing:(CGFloat)spacing {

    self.imageView.contentMode = UIViewContentModeCenter;
    self.titleLabel.contentMode = UIViewContentModeCenter;

    [self setImage:image forState:UIControlStateNormal];
    [self setTitle:title forState:UIControlStateNormal];

    [self resetTitleLabelWithPostiton:position spacing:spacing];
}

- (void)resetTitleLabelWithPostiton:(YSTitlePosition)position spacing:(CGFloat)spacing {
    CGSize imageSize = [self imageRectForContentRect:self.bounds].size;
    UIFont *font = self.titleLabel.font;
    CGSize titleSize = [self.titleLabel.text sizeWithAttributes: @{NSFontAttributeName : font}];
    UIEdgeInsets titleInset, imageInset;

    switch (position) {
        case YSTitlePositionLeft:
            titleInset = UIEdgeInsetsMake(0, 0, 0, -spacing / 2);
            imageInset = UIEdgeInsetsMake(0, -spacing / 2, 0, 0);
            break;
        case YSTitlePositionRight:
            titleInset = UIEdgeInsetsMake(0, -(imageSize.width * 2 + spacing / 2), 0, 0);
            imageInset = UIEdgeInsetsMake(0, 0, 0, -(titleSize.width * 2 + spacing / 2));
            break;
        case YSTitlePositionBottom:
            titleInset = UIEdgeInsetsMake(imageSize.height+spacing, -(imageSize.width), 0, 0);
            imageInset = UIEdgeInsetsMake(-titleSize.height-spacing, 0, 0, -titleSize.width);
            break;
        case YSTitlePositionTop:
            titleInset = UIEdgeInsetsMake(-(imageSize.height + titleSize.height + spacing) / 2, -(imageSize.width), 0, 0);
            imageInset = UIEdgeInsetsMake((imageSize.height + titleSize.height + spacing) / 2, 0, 0, -titleSize.width);
            break;
        default:
            titleInset = UIEdgeInsetsZero;
            imageInset = UIEdgeInsetsZero;
            break;
    }

    self.titleEdgeInsets = titleInset;
    self.imageEdgeInsets = imageInset;
}

@end
